import { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { ProductDetail } from "@/types/sku";
import { skuService } from "@/service/skuService";
import { toast } from "sonner";
import { cartService } from "@/service/cartService";

export default function Detail() {
  const { skuId } = useParams<{ skuId: string }>();
  const navigate = useNavigate();
  const [productDetail, setProductDetail] = useState<ProductDetail | null>(null);
  const [selectedSpecs, setSelectedSpecs] = useState<Record<number, number>>({});
  const [quantity, setQuantity] = useState(1);
  const [selectedImageIndex, setSelectedImageIndex] = useState(0);

  useEffect(() => {
    const fetchProduct = async () => {
      if (!skuId) return;

      try {
        const id = parseInt(skuId, 10);
        const data = await skuService.getSkuDetail(id);

        setProductDetail(data);

        // 初始化选中规格
        if (data?.specs) {
          const initialSpecs: Record<number, number> = {};
          const currentSku = data.skus.filter(sku => sku.id === id)[0]
          data.specs.forEach(spec => {
            spec.values.forEach(specValue => {
              if (currentSku.specValueIds.includes(specValue.id)) {
                initialSpecs[spec.id] = specValue.id
              }
            })
          })
          setSelectedSpecs(initialSpecs);
        }
      } catch (error) {
        console.error('获取商品详情失败', error);
      } finally {
      }
    };

    fetchProduct();
  }, [skuId]);

  // 处理规格选择
  const handleSpecChange = (specId: number, valueId: number) => {
    setSelectedSpecs(prev => ({
      ...prev,
      [specId]: valueId
    }));
  };

  // 获取匹配当前选择规格的SKU选项
  const getMatchingSku = () => {
    if (!productDetail) return null;

    // 判断是否所有规格都已选择
    const allSpecsSelected = productDetail.specs.every(spec =>
      selectedSpecs[spec.id] !== undefined
    );

    if (!allSpecsSelected) return null;

    return productDetail.skus.find(sku =>
      productDetail.specs.every(spec =>
        sku.specValueIds.includes(selectedSpecs[spec.id])
      )
    );
  };

  // 获取当前SKU的价格
  const getCurrentPrice = () => {
    const sku = getMatchingSku();
    return sku?.price;
  };

  // 获取当前SKU的库存
  const getCurrentStock = () => {
    return getMatchingSku()?.stock || 0;
  };

  // 添加到购物车
  const addToCart = () => {
    const sku = getMatchingSku();
    if (!sku) {
      toast.error("请选择完整规格");
      return;
    }
    const stock = getCurrentStock();
    if (stock && stock < quantity) {
      toast.error(`当前库存仅剩${stock}件`);
      return;
    }


    // 调用添加购物车的API
    cartService.addToCart(sku.id, quantity)
      .then(_ => toast.success(`已将${productDetail?.spu.title} x ${quantity}加入购物车`))
      .catch(_ => toast.error('添加购物车失败'));
  };



  if (!productDetail) {
    return (
      <div className="text-center py-12">
        <h2 className="text-2xl font-bold mb-4">商品不存在</h2>
        <Button onClick={() => navigate('/mall')}>返回首页</Button>
      </div>
    );
  }

  return (
    <div className="">
      <Button
        variant="ghost"
        className="mb-6"
        onClick={() => navigate('/mall')}
      >
        &larr; 返回首页
      </Button>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-8 mx-auto max-w-6xl">
        {/* 商品图片区 */}
        <div>
          <div className="w-100 overflow-hidden rounded-lg mb-4">
            <img
              src={productDetail.skus[selectedImageIndex].imageUrl}
              alt={productDetail.spu.title}
              className="w-full h-auto  object-cover rounded-lg transition-all duration-300 hover:scale-105"
            />
          </div>

          {/* 缩略图列表 */}
          {productDetail.skus.length >= 1 && (
            <div className="flex gap-2 overflow-x-auto pb-2">
              {productDetail.skus.map((sku, index) => (
                <div
                  key={index}
                  className={`w-16 h-16 rounded cursor-pointer border-2 ${selectedImageIndex === index ? 'border-blue-400' : 'border-transparent'
                    }`}
                  onClick={() => setSelectedImageIndex(index)}
                >
                  <img
                    src={sku.imageUrl}
                    alt={`缩略图 ${index + 1}`}
                    className="w-full h-full object-cover rounded"
                  />
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 商品信息区 */}
        <div>
          <h1 className="text-2xl font-bold mb-2">{productDetail.spu.title}</h1>
          <div className="text-xl font-semibold text-primary mb-4">
            ¥{getCurrentPrice()}
          </div>

          <div className="mb-6">
            <p className="text-gray-600">{productDetail.spu.description}</p>
          </div>

          {/* 规格选择 */}
          <Card className="mb-6">
            <CardContent className="pt-6">
              {productDetail.specs.map((spec) => (
                <div key={spec.id} className="mb-4">
                  <h3 className="text-sm font-medium mb-2">{spec.name}</h3>
                  <RadioGroup
                    value={selectedSpecs[spec.id]?.toString()}
                    onValueChange={(value) => handleSpecChange(spec.id, parseInt(value, 10))}
                    className="flex flex-wrap gap-2"
                  >
                    {spec.values.map((value) => (
                      <div key={value.id} className="flex items-center">
                        <RadioGroupItem
                          value={value.id.toString()}
                          id={`spec-${spec.id}-${value.id}`}
                          className="peer sr-only"
                        />
                        <Label
                          htmlFor={`spec-${spec.id}-${value.id}`}
                          className="px-3 py-1.5 border rounded-md peer-data-[state=checked]:bg-primary peer-data-[state=checked]:text-white cursor-pointer hover:bg-gray-100 peer-data-[state=checked]:hover:bg-primary"
                        >
                          {value.name}
                        </Label>
                      </div>
                    ))}
                  </RadioGroup>
                </div>
              ))}

              {/* 数量选择 */}
              <div className="mt-4">
                <h3 className="text-sm font-medium mb-2">数量</h3>
                <div className="flex items-center">
                  <Button
                    variant="outline"
                    size="icon"
                    disabled={quantity <= 1}
                    onClick={() => setQuantity(prev => Math.max(1, prev - 1))}
                  >
                    -
                  </Button>
                  <span className="mx-4 w-8 text-center">{quantity}</span>
                  <Button
                    variant="outline"
                    size="icon"
                    disabled={quantity >= getCurrentStock()}
                    onClick={() => setQuantity(prev => prev + 1)}
                  >
                    +
                  </Button>
                  <span className="ml-4 text-sm text-gray-500">
                    库存: {getCurrentStock()}
                  </span>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 操作按钮 */}
          <div className="flex gap-4">
            <Button
            variant="secondary"
              className="flex-1"
              onClick={addToCart}
              disabled={!getMatchingSku() || getCurrentStock() <= 0}
            >
              加入购物车
            </Button>
            <Button
              // variant="secondary"
              className="flex-1"
              onClick={() => {
                addToCart();
                navigate('/mall/cart');
              }}
              disabled={!getMatchingSku() || getCurrentStock() <= 0}
            >
              立即购买
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
} 